package com.long1008.service;

import com.long1008.pojo.Hr;
import com.long1008.pojo.MsgContent;
import com.long1008.pojo.RespPageEntity;
import com.long1008.pojo.SysMsg;
import com.long1008.common.HrUtils;
import com.long1008.mapper.SysMsgMapper;
import com.long1008.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class SysMsgService {
    @Autowired
    SysMsgMapper sysMsgMapper;
    @Autowired
    HrService hrService;

    @PreAuthorize("hasRole('ROLE_admin')")//只有管理员可以发送系统消息
    public boolean sendMsg(MsgContent msg) {
        int result = sysMsgMapper.sendMsg(msg);
        List<Hr> allHr = hrService.getAllHr();
        int result2 = sysMsgMapper.addMsg2AllHr(allHr, msg.getId());
        return result2==allHr.size();
    }

    public RespPageEntity getSysMsgByPage(Integer page, Integer size) {
        RespPageEntity pageEntity = new RespPageEntity();
        // 默认从0开始
        if (page != null && size != null) {
            page = (page-1)*size;
        }
        // 获取当前用户信息
        List<SysMsg> sysMsgs =  sysMsgMapper.getSysMsg(page, size, HrUtils.getCurrentHr().getId());
        pageEntity.setData(sysMsgs);
        // 获取当前用户信息总量
        Long totalCount = sysMsgMapper.getSysMsgCount(HrUtils.getCurrentHr().getId());
        pageEntity.setTotal(totalCount);
        return pageEntity;
    }

    public boolean markRead(Long flag) {
        if (flag != -1) {
            return sysMsgMapper.markRead(flag,HrUtils.getCurrentHr().getId())==1;
        }
        sysMsgMapper.markRead(flag,HrUtils.getCurrentHr().getId());
        return true;
    }
}
